#include "frmmain.h"
#include "frmserialport.h"
#include "frmtcpclient.h"
#include "frmdeviceconfig.h"
#include "frmdeviceupdate.h"
#include <QSerialPortInfo>
#include <QMessageBox>

frmmain::frmmain(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::frmmain),
    navButtonGroup(new QButtonGroup(this)),
    serialPort(this),
    tcpSocket(this),
    isSerialConnected(false),
    isTcpConnected(false),
    serialBuffer(""),
    tcpBuffer(""),
    serialPortPage(nullptr),
    tcpClientPage(nullptr),
    deviceConfigPage(nullptr),
    deviceUpdatePage(nullptr)
{
    ui->setupUi(this);

    // 1. 设置按钮为可选中
    ui->btnSerialPort->setCheckable(true);
    ui->btnTcpClient->setCheckable(true);
    ui->btnDeviceConfig->setCheckable(true);
    ui->btnDeviceUpdate->setCheckable(true);

    // 初始化按钮组
    navButtonGroup->addButton(ui->btnSerialPort, 0);
    navButtonGroup->addButton(ui->btnTcpClient, 1);
    navButtonGroup->addButton(ui->btnDeviceConfig, 2);
    navButtonGroup->addButton(ui->btnDeviceUpdate, 3);

    // 设置按钮组互斥
    navButtonGroup->setExclusive(true);

    // 设置按钮样式（优化：添加圆角和悬停效果）
    QString buttonStyle = R"(
        QPushButton {
            background-color: #F0F0F0;
            border: 1px solid #CCCCCC;
            border-radius: 5px;
            padding: 5px;
            font-size: 14px;
        }
        QPushButton:hover {
            background-color: #E0E0E0;
        }
        QPushButton:checked {
            background-color: #4A90E2;
            color: white;
            border: 1px solid #3A80E0;
        }
    )";

    // 应用样式到所有导航按钮
    ui->btnSerialPort->setStyleSheet(buttonStyle);
    ui->btnTcpClient->setStyleSheet(buttonStyle);
    ui->btnDeviceConfig->setStyleSheet(buttonStyle);
    ui->btnDeviceUpdate->setStyleSheet(buttonStyle);

    // 默认选中第一个按钮
    ui->btnSerialPort->setChecked(true);

    // 动态创建自定义控件
    serialPortPage = new frmserialport(this);
    tcpClientPage = new frmtcpclient(this);
    deviceConfigPage = new frmdeviceconfig(this);
    deviceUpdatePage = new frmdeviceupdate(this);

    // 将自定义控件添加到 stackedWidget 的页面
    ui->pageSerialPort->layout()->addWidget(serialPortPage);
    ui->pageTcpClient->layout()->addWidget(tcpClientPage);
    ui->pageNtripConfig->layout()->addWidget(deviceConfigPage);
    ui->pageMqttConfig->layout()->addWidget(deviceUpdatePage);

    // 初始化界面
    ui->responseTextEdit->append(QString::fromUtf8("上位机启动"));

    // 连接信号和槽
    connect(&serialPort, &QSerialPort::readyRead, this, &frmmain::on_serialPort_readyRead);
    connect(&tcpSocket, &QTcpSocket::connected, this, &frmmain::on_tcpSocket_connected);
    connect(&tcpSocket, &QTcpSocket::disconnected, this, &frmmain::on_tcpSocket_disconnected);
    connect(&tcpSocket, &QTcpSocket::readyRead, this, &frmmain::on_tcpSocket_readyRead);

    // 使用 QButtonGroup 的 buttonClicked 信号进行页面切换
    connect(navButtonGroup, QOverload<int>::of(&QButtonGroup::buttonClicked), this, &frmmain::on_navButtonClicked);
}

frmmain::~frmmain()
{
    if (isSerialConnected) {
        serialPort.close();
    }
    if (isTcpConnected) {
        tcpSocket.disconnectFromHost();
    }
    delete serialPortPage;
    delete tcpClientPage;
    delete deviceConfigPage;
    delete deviceUpdatePage;
    delete ui;
}

void frmmain::on_navButtonClicked(int index)
{
    // 检查索引是否有效
    if (index >= 0 && index < ui->stackedWidget->count()) {
        ui->stackedWidget->setCurrentIndex(index);
    } else {
        ui->responseTextEdit->append(QString::fromUtf8("错误：页面索引无效"));
    }
}

void frmmain::on_serialPort_readyRead()
{
    serialBuffer += QString::fromUtf8(serialPort.readAll());
    while (serialBuffer.contains("\r\n")) {
        int endIndex = serialBuffer.indexOf("\r\n");
        QString message = serialBuffer.left(endIndex).trimmed();
        serialBuffer = serialBuffer.mid(endIndex + 2);
        if (!message.isEmpty()) {
            ui->responseTextEdit->append(QString::fromUtf8("串口接收: ") + message);
            emit serialDataReceived(message); // 触发信号，通知接收到的串口数据
        }
    }
}

void frmmain::on_tcpSocket_connected()
{
    setIsTcpConnected(true);
    ui->responseTextEdit->append(QString::fromUtf8("TCP 连接成功"));
}

void frmmain::on_tcpSocket_disconnected()
{
    setIsTcpConnected(false);
    ui->responseTextEdit->append(QString::fromUtf8("TCP 连接断开"));
}

void frmmain::on_tcpSocket_readyRead()
{
    tcpBuffer += QString::fromUtf8(tcpSocket.readAll());
    while (tcpBuffer.contains("\r\n")) {
        int endIndex = tcpBuffer.indexOf("\r\n");
        QString message = tcpBuffer.left(endIndex).trimmed();
        tcpBuffer = tcpBuffer.mid(endIndex + 2);
        if (!message.isEmpty()) {
            ui->responseTextEdit->append(QString::fromUtf8("TCP 接收: ") + message);
            emit tcpDataReceived(message); // 触发信号，通知接收到的 TCP 数据
        }
    }
}